<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="70px">
      <el-form-item :label="t('supply.name')">
        <el-input
          v-model="form.name"
          clearable
          :placeholder="t('supply.name')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('supply.sup_type')">
        <el-select
          v-model="form.sup_type"
          :filterable="true"
          :placeholder="t('supply.sup_type')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in supTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('supply.phone')">
        <el-input
          v-model="form.phone"
          clearable
          :placeholder="t('supply.phone')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleAdd('add')">
        {{ t('supply.add') }}
      </el-button>
      <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatch('delete')">
        {{ t('supply.del') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <el-table
      :data="dataList"
      highlight-current-row
      stripe
      border
      v-loading="tableLoading"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column :label="t('expandCustomer.serialNumber')" prop="id" min-width="70" />
      <el-table-column
        :label="t('supply.name')"
        min-width="200"
        prop="name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.domain')"
        min-width="170"
        prop="domain"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.sup_type')"
        min-width="130"
        prop="sup_type"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(supTypeList, row.sup_type) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('supply.contact')"
        min-width="120"
        prop="contact"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.phone')"
        min-width="130"
        prop="phone"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.create_time')"
        min-width="180"
        prop="create_time"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.creator')"
        min-width="100"
        prop="creator"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(operatorList, row.creator) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('supply.update_time')"
        min-width="180"
        prop="update_time"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('supply.updater')"
        min-width="100"
        prop="updater"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(operatorList, row.updater) }}
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="300">
        <template #default="{ row }">
          <el-button @click="handleJump('edit', row)" size="small">
            {{ t('supply.edit') }}
          </el-button>
          <el-button @click="handleJump('table', row)" size="small">
            {{ t('retail.showGoods') }}
          </el-button>
          <el-button type="success" @click="handleJump('detail', row)" size="small">
            {{ t('supply.detail') }}
          </el-button>
          <el-button type="danger" @click="handleDelete('single', row)" size="small">
            {{ t('supply.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { getListApi, delListApi } from '@/api/supply'
import { ElButton } from 'element-plus'
import { getEnumApi } from '@/api/supply'
import { ElMessage, ElMessageBox } from 'element-plus'

const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const paginationTotal = ref<number>(0)
const multipleSelection = ref<any[]>([])

const supTypeList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])

const form = ref<Record<string, any>>({
  name: '',
  sup_type: '',
  phone: '',
  category: 1,
  pageIndex: 1,
  pageSize: 15
})

//点击跳转到新增
const handleAdd = (type: string) => {
  push({ path: `/channelManage/supplier/supplierManage/${type}` })
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

const handleJump = (type: string, row?: Record<string, any>) => {
  push({
    path: `/channelManage/supplier/supplierManage/${type}`,
    query: { [(row && 'id') as string]: row?.id }
  })
}

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

//批量操作
const handleBatch = async (type: string) => {
  const functionMap = {
    delete: () => handleDelete('batch', {})
  }
  if (functionMap[type]) functionMap[type]()
}

//删除某一行
const handleDelete = (type: string, row: Record<string, any>) => {
  ElMessageBox.confirm(t('purchase.logistics.confirmDeletion'), t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const ids =
        type === 'single'
          ? [row.id]
          : multipleSelection.value.map((item: Record<string, any>) => item.id)
      await delListApi(ids)
      ElMessage.success(t('purchase.logistics.deleteSuccess'))
      await initialize()
    })
    .catch(() => {})
}

const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  supTypeList.value = resp.data.sup_type
  operatorList.value = resp.data.operator
}

//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

//重置查询项
const reset = () => {
  form.value = {
    name: '',
    sup_type: '',
    category: 1,
    phone: '',
    pageIndex: 1,
    pageSize: 15
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})
</script>

<style lang="less" scoped></style>
